package cn.zzuisa.deutsch.controller;


import cn.zzuisa.deutsch.base.R;
import cn.zzuisa.deutsch.entity.Member;
import cn.zzuisa.deutsch.entity.request.LoginCode;
import cn.zzuisa.deutsch.entity.request.LoginCodeRequestRetu;
import cn.zzuisa.deutsch.entity.request.WXLoginRes;
import cn.zzuisa.deutsch.log.annotation.BussinessLog;
import cn.zzuisa.deutsch.service.MemberService;
import cn.zzuisa.deutsch.utils.JacksonJsonUtil;
import cn.zzuisa.deutsch.utils.MemberSessionKeyMap;
import cn.zzuisa.deutsch.utils.NetIOUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Enumeration;

/**
 * <p>
 * 注册会员 前端控制器
 * </p>
 *
 * @author Ao
 * @since 2018-11-30
 */
@RestController
@RequestMapping("/user/member")
public class MemberController {


    private String APPID = "wx60698ff708cef81c";

    private String APP_SECRET = "b3bda4d6bf53cdd85e01d969c6b95c02";

    @Autowired
    MemberService memberService;


    /**
     * 小程序登录
     */
    @BussinessLog("登录")
    @PostMapping("/wxlogin")
    public R wxLogin(@RequestBody(required = true) LoginCode code, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("code" + code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + APP_SECRET + "&js_code=" + code.getCode() + "&grant_type=authorization_code";
        String str = NetIOUtils.get(url);
        LoginCodeRequestRetu lu = JacksonJsonUtil.toObject(str, LoginCodeRequestRetu.class);
        if ("40029".equals(lu.getErrcode())) {
            return R.error("code 无效");
        }
        if ("45011".equals(lu.getErrcode())) {
            return R.error("频率限制，每个用户每分钟100次");
        }

//		自定义登录态，不用了
//		WXLoginRes loginRes = new WXLoginRes();
//		loginRes.setSession_key(StringUtils.MD5_SHA(lu.getSession_key()+lu.getOpenid(), "MD5"));
        if (lu.getErrcode() == null) {
//			MemberSessionKeyMap.put(loginRes.getSession_key(), new MemberInfo());
            Member one = memberService.getOne(new QueryWrapper<Member>()
                    .eq("open_id", lu.getOpenid()));
            if (one == null) {
                // openID 没有查询到用户， 首次授权登录
                one = new Member().setHeadImg(code.getHeaderImg())
                        .setName(code.getName())
                        .setOpenId(lu.getOpenid())
                        .setLevel(1)
                        .setAddress(code.getProvince() + " " + code.getCity())
                        .setLastLogin(LocalDateTime.now())
                        .setCreateTime(LocalDateTime.now())
                        .setSex(code.getGender() == 1 ? "男" : "女");// 用户ID name headImg

                System.out.println("one new1:"+one);
                memberService.save(one);
                one = memberService.getOne(new QueryWrapper<Member>().eq("open_id", lu.getOpenid()));
                System.out.println("one new:"+one);
            }
            one.setLastLogin(LocalDateTime.now()).setExperience(one.getExperience() + 3).setStatus(one.getStatus() + 1);
            memberService.updateById(one);
            HttpSession session = request.getSession();
            MemberSessionKeyMap.put(lu.getSession_key(), one);
            session.setAttribute("member", one);

            Enumeration er = request.getHeaderNames();//获取请求头的所有name值
        while(er.hasMoreElements()){
            String name	=(String) er.nextElement();
            String value = request.getHeader(name);
            System.out.println("-=-=-=-"+name+"="+value);
        }
            WXLoginRes res = new WXLoginRes();
            System.out.println("SESSION"+lu.getSession_key());
            System.out.println("SESSIONNMSG"+lu.getErrmsg());
            res.setHeadImg(one.getHeadImg());
            res.setName(one.getName());
            res.setUserId(one.getId());
            return R.success(res);
        }
        return R.success("未知错误");
    }

}
